<script setup>
import { computed, ref, watch } from 'vue'

const productList = ref([
  { id: 1, name: 'Apple', quantity: 0, price: 2.5 },
  { id: 2, name: 'Banana', quantity: 0, price: 1.2 },
  { id: 3, name: 'Orange', quantity: 0, price: 3.0 },
  { id: 4, name: 'Milk', quantity: 0, price: 4.5 }
])

const selectedList = ref([])
const discount = ref(0)
const totalPrice = computed(() => selectedList.value.reduce((prev, p) => prev + p.quantity * p.price, 0))

function handleSelect(product) {
  if (!selectedList.value.find(p => p.id === product.id)) {
    selectedList.value = [...selectedList.value, product]
    return
  }
  selectedList.value = selectedList.value.filter(p => p.id !== product.id)
}

function addQuantity(id) {
  const product = productList.value.find(p => p.id === id)
  product.quantity += 1
}

function subQuantity(id) {
  const product = productList.value.find(p => p.id === id)
  product.quantity -= 1
}

watch(
  () => selectedList.value.reduce((prev, p) => prev + p.quantity, 0),
  totalQuantity => {
    if (totalQuantity < 3 && totalQuantity === 2) return (discount.value = 0.9)
    if (totalQuantity >= 3) return (discount.value = 0.8)
    discount.value = 0.95
  }
)
</script>

<template>
  <main class="w-xl space-y-2 rounded-2xl bg-white p-6 shadow select-none">
    <div class="grid grid-cols-3" v-for="product in productList" :key="product.id">
      <div class="col-span-1">
        <input class="mr-2" type="checkbox" :id="product.name" :name="product.name" @change="handleSelect(product)" />
        <label class="font-bold" :for="product.name">{{ product.name }}</label>
      </div>

      <div class="col-span-1 text-center">${{ product.price }}</div>

      <div class="col-span-1 flex justify-end gap-2">
        <button class="btn size-5 self-center leading-1" @click="addQuantity(product.id)">+</button>
        <span>{{ product.quantity }}</span>
        <button
          class="btn size-5 self-center leading-1"
          @click="subQuantity(product.id)"
          :disabled="product.quantity === 0"
        >
          -
        </button>
      </div>
    </div>

    <div class="text-center font-bold text-red-400">总价：${{ (totalPrice * discount).toFixed(2) }}</div>
  </main>
</template>
